package com.lx.txx.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lx.bean.Result;
import com.lx.txx.entity.BizException;
import com.lx.txx.entity.TxxUser;
import com.lx.txx.service.ITxxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpSession;

/**
 * <p>
 * 天下行租车-用户表-4 前端控制器
 * </p>
 *
 * @author lx
 * @since 2024-12-30
 */
@RestController
@RequestMapping("/txxUser")
public class TxxUserController {

    @Autowired
    ITxxUserService txxUserService;

    @RequestMapping("reSetPwd")
    public Result reSetPwd(String ename, String vcode, String pwd, String repwd,
                           HttpSession session){
        // @SessionAttribute String forgetVcode 如果 forgetVcode 失效, 会导致报400错
        String forgetVcode = (String) session.getAttribute("vcode");
        LambdaUpdateWrapper<TxxUser> lqw = new LambdaUpdateWrapper<>();
        lqw.eq(TxxUser::getEname, ename);
        TxxUser user = txxUserService.getOne(lqw);
        if ( forgetVcode== null) {
            return new Result(-1, "验证码已经失效或未发送", null);
        }else if(user == null){
            return new Result(-2, "用户名不存在", null);
        }else if(!vcode.equalsIgnoreCase(forgetVcode)){
            return new Result(-3, "验证码错误", null);
        }else if(!pwd.equals(repwd)){
            return new Result(-4, "两次密码不一致", null);
        }else if(pwd.equals("") || repwd.equals("")){
            return new Result(-5, "密码不能为空", null);
        }else if(vcode.equals("")){
            return new Result(-6, "验证码不能为空", null);
        }
        LambdaUpdateWrapper<TxxUser> lqw2 = new LambdaUpdateWrapper<>();
        lqw2.eq(TxxUser::getId, user.getId());
        user.setPassword(pwd);
        txxUserService.saveOrUpdate(user);
        session.removeAttribute("vcode");
        session.removeAttribute("forgetUser");
        return new Result(1, "密码重置成功", null);
    }
    @RequestMapping("myinfo")
    public Result myinfo(@SessionAttribute(required = false) TxxUser loginedUser,
                         HttpSession session) throws BizException {
        System.out.println(loginedUser);
        if(loginedUser == null){
                throw new BizException("未登录", null);
        }
        return new Result(1, "已登录", loginedUser);
    }


}
